package com.atguigu.spring5.dao;

import com.atguigu.spring5.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao {

    /**
     * 使用jdbcTemplate模板来实现数据库操作
     */
    //注入jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //添加方法
    @Override
    public void add(Book book) {
        //创建sql语句
        String sql = "insert into t_book values(?,?,?)";
        //创建可变参数数组,设置 sql 语句值
        Object[] args = {book.getUserId(), book.getUsername(), book.getUstatus()};
        //调用方法实现
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    //删除方法
    @Override
    public void delete(String id) {
        //创建sql语句
        String sql = "delete  from t_book where user_id=?";
        //调用方法实现
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    //修改方法
    @Override
    public void update(Book book) {
        //创建sql语句
        String sql = "update t_book set username=?,ustatus=? where user_id=?";
        //创建可变参数数组,设置 sql 语句值
        Object[] args = {book.getUsername(), book.getUstatus(), book.getUserId()};
        //调用方法实现
        int update = jdbcTemplate.update(sql, args);
//        int update = jdbcTemplate.update(sql, book.getUsername(),book.getUstatus(),book.getUserId());
        System.out.println(update);
    }

    //查询方法
    //查询结果是，返回一个值
    @Override
    public int selectCount() {
        //创建sql语句
        String sql = "select count(*) from t_book ";
        //调用方法实现
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);//第二个参数就是返回值类型,注意与sql返回值类型要匹配
        return count;
    }

    //查询结果，返回一个对象
    @Override
    public Book findBookInfo(String id) {
        String sql = "select * from t_book where user_id=?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        return book;
    }

    //查询结果，返回一个集合
    @Override
    public List<Book> findListInfo() {
        String sql = "select * from t_book";
        List<Book> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return list;
    }

    //批量操作
    @Override
    public void batchAddBook(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}
